/***********************************************************************************
  Copy right:     2020-2030 ESP8266 STA demo.
  Author:         hujianguo
  Date:           2022.6.19
  Description:    服务端STA服务处理程序
***********************************************************************************/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

/*****************AP设置项 *****************/
const char *STAssid = "apapapap" ;        //AP名字（目标连接的名字）
const char *STApassword = "12345678";   //AP密码（目标连接的密码）
int Relay = 0;                                      //设置继电器控制IO（这里为dio0）

/****************UDP设置项 *****************/
unsigned int read_Port = 11234;       //监听端口
unsigned int send_Port = 11235;        //发送端口
char readdata[512];                       //数据缓存
WiFiUDP Udp;                               //定义udp
IPAddress ap_ip(192, 168, 2, 1);        //AP的ip地址

/**************** 串口设置项 *****************/
static String inputString = "";
static bool stringComplete = false;

static String OpenString = "opena_success";
static String CloseString = "closea_success";
static String ErrorString = "error";
/****************io设置项 *****************/


//初始化io
void init_IO()
{
  pinMode(Relay, OUTPUT);//设置指定io为输出模式
  digitalWrite(Relay, 0);//初始化为低电平，断开继电器，关闭灯状态（板载led和继电器并联，状体一致）先默认关闭
}

void setup()
{
  Serial.begin(115200);
  Serial.println("");
  Serial.printf("***** 串口初始化完成 *****");
  //初始化需要的IO引脚
  init_IO();
  //初始化wifi为ap模式
  init_STA();
  //UDP设置监听指定端口
  Udp.begin(read_Port);
}

void loop()
{
  Udp_Handler(Read_Udp());
}

//初始化连接AP
void init_STA()
{
  IPAddress local_ip(192, 168, 2, 2);
  IPAddress arg1(192, 168, 2, 1);
  IPAddress arg2(255, 255, 255, 0);
  IPAddress arg3(192, 168, 2, 1);
  IPAddress dns2(192, 168, 2, 1);
  WiFi.disconnect();
  WiFi.config(local_ip, arg1, arg2, arg3, dns2);
  WiFi.mode(WIFI_STA);
  WiFi.begin(STAssid, STApassword);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  //Serial.printf("WiFi Connect success.");
  //几句提示
  Serial.println("");
  Serial.println("WiFi Connect success.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

//自定义函数,将接收的数据，以String类型返回，方便分析处理
String Read_Udp()
{
  String data = "";
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    memset(readdata, 0x00, sizeof(readdata));
    Udp.read(readdata, 511);
    Udp.flush();
    for (int i = 0; i < packetSize; i++)
    {
      data += readdata[i];
    }
//    Serial.println(data);
  }
  return data;
}

/************自定义函数，对接收数据分析处理************/
void Udp_Handler(String data)
{
  if (data != "")
  {
    if (data == "open_a\n")
    {
      digitalWrite(Relay, HIGH);
      Serial.println(data);
      //Serial.println("open_success\r\n");
      Udp.beginPacket(ap_ip, send_Port);
      Udp.print(OpenString);
      Udp.endPacket();
    }
    else if (data == "close_a\n")
    {
      digitalWrite(Relay, LOW);
      Serial.println(data);
      //Serial.println("close_success\r\n");
      Udp.beginPacket(ap_ip, send_Port);
      Udp.print(CloseString);
      Udp.endPacket();
    }
    else
    {
      digitalWrite(Relay, LOW);
      Serial.println(data);
      //Serial.println("error\r\n");
      //myPrint("error", 0);
      Udp.beginPacket(ap_ip, send_Port);
      Udp.print(ErrorString);
      Udp.endPacket();
    }
  }
  data = "";
}
